package com.tedu.myfirstspringboot.controller;

import com.tedu.myfirstspringboot.entity.Article;
import com.tedu.myfirstspringboot.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {
    //该对象表示保存所有用户信息的目录
    private static File userDir;

    static{
        userDir = new File("./users");
        if(!userDir.exists()){
            userDir.mkdirs();
        }
    }

    @RequestMapping("/articleList")
    public void articleList(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始处理动态数据");
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String content = request.getParameter("content");
        File articleDir;

        articleDir = new File("./articles");

        //1准备页面上要展示的所有数据
        List<Article> articleList = new ArrayList<>();
        File file = new File(articleDir,title+".obj");
        //获取users目录中的所有obj文件
        File[] subs = articleDir.listFiles(f->f.getName().endsWith(".obj"));
        for(File sub : subs){
            try (
                    FileInputStream fis = new FileInputStream(sub);
                    ObjectInputStream ois = new ObjectInputStream(fis);
            ){
                Article article = (Article) ois.readObject();
                articleList.add(article);
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.println("<!DOCTYPE html>");
            pw.println("<html lang=\"en\">");
            pw.println("<head>");
            pw.println("<meta charset=\"UTF-8\">");
            pw.println("<title>文章列表</title>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("<center>");
            pw.println("<h1>文章列表</h1>");
            pw.println("<table border=\"1\">");
            pw.println("<tr>");
            pw.println("<td>标题</td>");
            pw.println("<td>作者</td>");
            pw.println("</tr>");

            for(Article article : articleList) {
                pw.println("<tr>");
                pw.println("<td>"+article.getTitle()+"</td>");
                pw.println("<td>"+article.getAuthor()+"</td>");
                pw.println("</tr>");
            }

            pw.println("</table>");
            pw.println("</center>");
            pw.println("</body>");
            pw.println("</html>");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/userList")
    public void userList(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始处理动态数据");
        //1准备页面上要展示的所有数据
        List<User> userList = new ArrayList<>();
        //获取users目录中的所有obj文件
        File[] subs = userDir.listFiles(f->f.getName().endsWith(".obj"));
        for(File sub : subs){
            try (
                    FileInputStream fis = new FileInputStream(sub);
                    ObjectInputStream ois = new ObjectInputStream(fis);
            ){
                User user = (User)ois.readObject();
                userList.add(user);
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.println("<!DOCTYPE html>");
            pw.println("<html lang=\"en\">");
            pw.println("<head>");
            pw.println("<meta charset=\"UTF-8\">");
            pw.println("<title>用户列表</title>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("<center>");
            pw.println("<h1>用户列表</h1>");
            pw.println("<table border=\"1\">");
            pw.println("<tr>");
            pw.println("<td>用户名</td>");
            pw.println("<td>密码</td>");
            pw.println("<td>昵称</td>");
            pw.println("<td>年龄</td>");
            pw.println("</tr>");

            for(User user : userList) {
                pw.println("<tr>");
                pw.println("<td>"+user.getUsername()+"</td>");
                pw.println("<td>"+user.getPassword()+"</td>");
                pw.println("<td>"+user.getNickname()+"</td>");
                pw.println("<td>"+user.getAge()+"</td>");
                pw.println("</tr>");
            }

            pw.println("</table>");
            pw.println("</center>");
            pw.println("</body>");
            pw.println("</html>");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/loginUser")
    public void login(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始处理用户登录...");
        //1获取用户提交的登录信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //必要的信息验证工作
        if(username==null||username.trim().isEmpty()||
                password==null||password.trim().isEmpty()){
            //输入信息有误
            try {
                response.sendRedirect("/login_info_error.html");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //根据该登录用户的用户名去读取曾经的注册信息
        File file = new File(userDir,username+".obj");
        //判断该文件是否存在,若不存在则说明用户名输入错误(没有此用户)
        if(file.exists()){
            //存在,则读取该注册用户信息
            try (
                    FileInputStream fis = new FileInputStream(file);
                    ObjectInputStream ois = new ObjectInputStream(fis);
            ){
                User user = (User)ois.readObject();
                //用登录的密码和注册时的密码进行比对
                if(password.equals(user.getPassword())){
                    //密码正确则说明登录成功
                    response.sendRedirect("/login_success.html");
                    return;
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }else{
            //登录失败
            try {
                response.sendRedirect("/login_fail.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }



    /**
     * 处理用户注册操作
     * @param request   请求对象,该对象内容保存的是浏览器发送过来的内容
     * @param response  响应对象,该对象保存我们要给浏览器发送的内容
     */
    @RequestMapping("/regUser")
    public void reg(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理注册!!!!");
        /*
            1:获取用户在注册页面上输入的注册信息
            2:将该用户信息保存
            3:回复注册结果页面
         */
        //1
        //这里的参数要与页面上输入框的名字一致!
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");

        if(username==null||username.trim().isEmpty()||
                password==null||password.trim().isEmpty()||
                nickname==null||nickname.trim().isEmpty()||
                ageStr==null||ageStr.trim().isEmpty()||
                !ageStr.matches("[0-9]+")
        ){
            try{
                response.sendRedirect("/reg_info_error.html");
                return;
            }catch (IOException e){
                e.printStackTrace();
            }

        }

        int age = Integer.parseInt(ageStr);//将年龄转换为int值
        System.out.println(username+","+password+","+nickname+","+ageStr);

        //2
        User user = new User(username,password,nickname,age);
        //表示该用户对应的obj文件
        /*
            File的构造器
            File(File parent,String child);
            当前创建出来的File对象表达的是child,但是它在parent指定的目录中
         */
        File file = new File(userDir,username+".obj");
        if(file.exists()){
            try{
                response.sendRedirect("/have_user.html");
                return;
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        try(
                FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(user);
            //3通过响应对象告诉浏览器请求注册成功页面看结果.
            response.sendRedirect("/reg_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}
